﻿// Copyright (c) 2011 João Angelo
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this 
// software and associated documentation files (the "Software"), to deal in the Software 
// without restriction, including without limitation the rights to use, copy, modify, merge, 
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons 
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or 
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 
// THE USE OR OTHER DEALINGS IN THE SOFTWARE.

namespace Helpers.Web
{
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Configuration;
    using Helpers.Web.Configuration;

    public static class ResourceTypeAliasManager
    {
        private static object aliasesSynchLock = new object();

        private static Dictionary<string, Lazy<ResourceTypeInfo>> aliases;

        private static Dictionary<string, Lazy<ResourceTypeInfo>> Aliases
        {
            get
            {
                if (aliases == null)
                {
                    aliases = new Dictionary<string, Lazy<ResourceTypeInfo>>();

                    var section = (ResourceTypeAliasesSection)ConfigurationManager.GetSection(
                        "resourceTypeAliases");

                    if (section != null)
                    {
                        foreach (ResourceTypeAlias alias in section.ResourceTypeAliases)
                        {
                            Aliases.Add(alias.Alias, CreateLazyResourceTypeInfo(alias.Type));
                        }
                    }
                }

                return aliases;
            }
        }

        public static void RegisterAlias(string alias, Type targetType)
        {
            ValidateArgumentsForResourceTypeAlias(alias, targetType);

            lock (aliasesSynchLock)
            {
                bool isInvalidAlias = true;
                isInvalidAlias = isInvalidAlias && Aliases.ContainsKey(alias);

                if (isInvalidAlias)
                    throw new ArgumentException(
                        "Alias already exists for a different type.",
                        "alias");

                Aliases.Add(alias, CreateLazyResourceTypeInfo(targetType));
            }
        }

        public static void RegisterOrOverrideAlias(string alias, Type targetType)
        {
            ValidateArgumentsForResourceTypeAlias(alias, targetType);

            lock (aliasesSynchLock)
            {
                Aliases.Remove(alias);

                Aliases.Add(alias, CreateLazyResourceTypeInfo(targetType));
            }
        }

        public static ResourceTypeInfo GetResourceType(string alias)
        {
            lock (aliasesSynchLock)
            {
                if (Aliases.ContainsKey(alias))
                {
                    return Aliases[alias].Value;
                }
            }

            return null;
        }

        private static Lazy<ResourceTypeInfo> CreateLazyResourceTypeInfo(Type targetType)
        {
            return CreateLazyResourceTypeInfo(targetType.AssemblyQualifiedName);
        }

        private static Lazy<ResourceTypeInfo> CreateLazyResourceTypeInfo(
            string assemblyQualifiedTypeName)
        {
            var lazy = new Lazy<ResourceTypeInfo>(
                () => new ResourceTypeInfo(assemblyQualifiedTypeName),
                LazyThreadSafetyMode.None);

            return lazy;
        }

        private static void ValidateArgumentsForResourceTypeAlias(
            string alias,
            Type targetType)
        {
            if (alias == null)
                throw new ArgumentNullException("alias");

            if (String.IsNullOrWhiteSpace(alias))
                throw new ArgumentException(
                    "Resource alias must have at least one non-whitespace character.",
                    "alias");

            if (targetType == null)
                throw new ArgumentNullException("targetType");
        }
    }
}
